package org.kukker.activity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.kukker.DBHelper;
import org.kukker.R;
import org.kukker.app.KukkerApp;
import org.kukker.dialog.AboutDialog;
import org.kukker.dialog.PreferenceDialog;
import org.kukker.event.Event;
import org.kukker.event.EventSearchParameters;
import org.kukker.event.IEventSearchListener;
import org.kukker.list.IKukkerListItemListener;
import org.kukker.list.IKukkerListItemView;
import org.kukker.list.KukkerListAdapter;
import org.kukker.list.KukkerListItemView;
import org.kukker.list.KukkerListView;
import org.kukker.upcoming.UpcomingEvent;
import org.kukker.upcoming.UpcomingWebService;
import org.kukker.view.EventDetailView;
import org.kukker.view.ISearchEventsInputListener;
import org.kukker.view.SearchEventsInput;
import org.kukker.view.EventDetailView.IEventDetailViewListener;
import org.xml.sax.SAXException;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.Menu.Item;
import android.view.View.OnClickListener;
import android.view.View.OnPopulateContextMenuListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsoluteLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.ContextMenuInfo;
import android.xml.dom.DocumentImpl;
import android.widget.CompoundButton.OnCheckedChangeListener;


public class BrowseSavedEventsActivity extends ListActivity implements IContextMenuWatcher{

	enum UserActivity {
		VIEW_EVENTDETAILS, VIEW_EVENTSEARCHRESULTS;
	}

	/*
	 * enum EventItemContextMenuOptions { SAVE_EVENT (0,0), FORWARD_EVENT (0,0),
	 * SHOW_DETAILS(0,0), CANCEL (0,0);
	 * 
	 * public int group; public int id;
	 * 
	 * private EventItemContextMenuOptions(int group,int id){ this.group =
	 * group; this.id = id; } }
	 */
	
	private Dialog mDialogSearch;
	private Dialog mDialogAbout;
	private Dialog mDialogPreferences;
	private Resources mResources;

	// flags
	public boolean mContextIsShown = false;
	
	// context menu options
	private static final int CMO_EVENT_SAVETOLOCAL = 0;
	private static final int CMO_EVENT_REMOVEFROMLOCAL = 1;
	private static final int CMO_EVENT_FORWARD = 2;
	private static final int CMO_EVENT_CANCEL = 3;
	private static final int CMO_EVENT_SHOWDETAILS = 4;
	private static final int CMO_EVENT_EDITDETAILS = 5;
	
	// options menu options
	private static final int OMO_SEARCHPUBLICEVENTS = 1;
	private static final int OMO_SEARCHSAVEDEVENTS = 2;
	private static final int OMO_SAVETOLOCAL = 3;
	private static final int OMO_CREATEEVENT = 4;
	private static final int OMO_DELETEFROMLOCAL = 5;
	private static final int OMO_SENDTOFRIENDS = 6;
	private static final int OMO_SHOWDETAILS = 7;
	
	private static final int OMO_PREFERENCES = 8;
	private static final int OMO_TIPS = 9;

	// hack
	// TODO re-architect this from db.
	private static final int ORIGIN_ID_LOCAL = 0;
	private static final int ORIGIN_ID_UPCOMING = 1;

	private UserActivity mUserActivity = UserActivity.VIEW_EVENTDETAILS;

	private KukkerListView eventListView;
	private KukkerListAdapter eventListAdapter;
	private EventDetailView eventDetailView;
	private SearchEventsInput eventSearchInput;

	private View eventLayout;

	UpcomingWebService uws;
	private DBHelper dbHelper;
	private String debugtag0 = "Kukker.java";

	private EventSearchParameters mEventSearchParams;

	// containers
	private View eventsSearchResultContainer;
	private View eventsSearchInputContainer;
	private Event event0;

	// listeners
	IEventDetailViewListener mEventDetailViewListener;
	IKukkerListItemListener mKukkerListItemListener;
	IEventSearchListener mEventSearchUpcomingListener;
	OnPopulateContextMenuListener mOnPopulateContextMenuListener;

	private int screenWidth;
	private int screenHeight;

	SearchEventsRunnable ser = new SearchEventsRunnable();

	private void setSearchParameters(EventSearchParameters esp) {
		this.mEventSearchParams = esp;

	}

	private ISearchEventsInputListener mSearchEventsInputListener;

	private void initListeners() {
		this.mSearchEventsInputListener = new ISearchEventsInputListener() {
			public void OnSearchClicked(final Properties params) {
				// eventSearchInput.setDetectIncomingEvents(false);
				// findViewById(R.id.eventsearchinput_container).setVisibility(View.GONE);
				// eventSearchInput.setVisibility(View.GONE);
				// eventListView.setDetectIncomingEvents(true);

				//Log.i("debug", "doAnim4");

				ser = new SearchEventsRunnable();
				ser.setSearchParameters(params);

				Handler handler = KukkerApp.mUpcomingLocalService.mServiceHandler;
				handler.post(ser);

				/*
				 * if(handler != null){ Message msg =
				 * KukkerApp.mUpcomingLocalService.mServiceHandler.obtainMessage();
				 * msg.what = 2; msg.obj = params; handler.dispatchMessage(msg); }
				 */

				doAnim4();
				// updateResultsList(params);
			}
		};

		this.mEventSearchUpcomingListener = new IEventSearchListener() {
			public void onEventFound(Event event) {
				// Log.i("db","onEventFound, name:"+event.name);
				Event savedRecord = dbHelper
						.fecthEventUsingRemoteId(event.remoteId);
				if (savedRecord != null) {
					// Log.i("db","saved found id:"+event.remoteId);
					event.setIsSaved(true);
				} else {
					// Log.i("db","not found in local db, id:"+event.remoteId);
				}
			}
		};

		this.mEventDetailViewListener = new IEventDetailViewListener() {

			@Override
			public void onKeyRightUp() {
				/*
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onKeyRightUp"

				+ "]");
				*/
				
				// go back to search results
			
			}

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				//go back to events list
				//mUserActivity = mUserActivity.VIEW_EVENTSEARCHRESULTS;
				//doAnim2();
			}

			@Override
			public void onClickDCenter() {
				// TODO Auto-generated method stub
				mUserActivity = UserActivity.VIEW_EVENTSEARCHRESULTS;
				doAnim2();
			}

		};

		this.mKukkerListItemListener = new IKukkerListItemListener() {

			@Override
			public void onListItemKeyLeftDown(IKukkerListItemView view) {
/*
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyLeftDown "

				+ "]");
*/

				
			}

			@Override
			public void onListItemKeyLeftUp(IKukkerListItemView view) {
				// TODO Auto-generated method stub
/*
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyLeftUp"

				+ "]");
*/
				
				
			}

			@Override
			public void onListItemKeyRightDown(IKukkerListItemView view) {
			}

			@Override
			public void onListItemKeyRightUp(IKukkerListItemView view) {
				/*
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]"
						+ "[" + "]" + "[" + "onListItemKeyRightUp" + "]");
*/
				
				//eventListView.setDetectIncomingEvents(false);

				//doAnim3();

				// dbHelper.deleteEventUsingRemoteId(data.remoteId);
				// dbHep

				view.right();
			}

			@Override
			public void onListItemKeyLeftClick(IKukkerListItemView view) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onListItemKeyDCenterClick(
					IKukkerListItemView view) {
				/*
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyDCenterClick"

				+ "]");
*/				
				
				/* DISABLED BECAUSE TOO BUGGY 
				// DISPLAY CONTEXT MENU BY DISPATCHING MOTIONEVENT
				int pos = eventListView.getSelectedItemPosition();
				KukkerListItemView childView =(KukkerListItemView) eventListView.getChildAt(pos);
				int childPos[] = new int[2];
				childView.getAbsoluteLocationOnScreen(childPos);
				int w = childView.getWidth();
				int h = childView.getHeight();
				MotionEvent ev = new MotionEvent(0,200,MotionEvent.ACTION_DOWN,childPos[0],childPos[1]);
				dispatchTouchEvent(ev);
				Log.i("debug","DCENTER:, pos:"+pos);
				*/
				
				// saveEvent();
				
				mUserActivity = UserActivity.VIEW_EVENTDETAILS;
				
				event0 = view.getData();

				eventListView.storeLastSelectedItem();
				eventListView.setActivated(false);				
				
				doAnim1();
				
			}

			@Override
			public void onListItemKeyMenuClick(IKukkerListItemView view) {
				// TODO Auto-generated method stub
				Log.i(debugtag0, "[" + this.getClass().getSimpleName() + "]" +

				"[" +

				"]"

				+ "[" + "onListItemKeyMenuClick"

				+ "]");

				// View aView = eventListView.getSelectedView();
				// if(aView != null){
				// int loc[] = new int[2];
				// aView.getAbsoluteLocationOnScreen(loc);

			}

		};

		this.mOnPopulateContextMenuListener = new OnPopulateContextMenuListener() {
			public void onPopulateContextMenu(ContextMenu contextmenu,
					View view, Object obj) {

				// Log.i("contextmenu","populate");
				
				try{
				//mContextIsShown = true;
	
				KukkerListView lv = (KukkerListView) view;
				int pos = lv.getLastPressedDownItemPosition();
				Object object = lv.getAdapter().getItem(pos);
				String className = object.getClass().getName();
				Log.i("debug",object.getClass().getName());
				

				if(className.compareTo("org.kukker.upcoming.UpcomingEvent") == 0){
					// create menu items
					Item showDetailsMenuItem = contextmenu.add(0,
							KukkerApp.OptionsMenu.CMO_EVENT_SHOWDETAILS,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_SHOWDETAILS);		
					Item saveMenuItem = contextmenu.add(0, 
							KukkerApp.OptionsMenu.CMO_EVENT_SAVETOLOCAL,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_SAVETOLOCAL);
					Item forwardMenuItem = contextmenu.add(0,
							KukkerApp.OptionsMenu.CMO_EVENT_FORWARD,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_FORWARD);
					Item removeFromLocalMenuItem = contextmenu.add(0,
							KukkerApp.OptionsMenu.CMO_EVENT_REMOVEFROMLOCAL, 
							KukkerApp.OptionsMenuLabel.CMO_EVENT_REMOVEFROMLOCAL);
					Item cancelMenuItem = contextmenu.add(0, 
							KukkerApp.OptionsMenu.CMO_EVENT_CANCEL,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_CANCEL);
					//UpcomingEvent data = (UpcomingEvent) object;
					// hide or show menu items based on data.
					/*
					boolean isSavedToLocal = data.getIsSaved();
					if (isSavedToLocal) {
						saveMenuItem.setShown(false);
						removeFromLocalMenuItem.setShown(true);
					} else {
						saveMenuItem.setShown(true);
						removeFromLocalMenuItem.setShown(false);
					}
					*/
				}else if(className.compareTo("org.kukker.event.Event") ==0 ){
					
					Item showDetailsMenuItem = contextmenu.add(
							0,
							CMO_EVENT_SHOWDETAILS,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_SHOWDETAILS);	
					Item editDetailsMenuItem = contextmenu.add(
							0, 
							CMO_EVENT_EDITDETAILS,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_EDIT);
					Item forwardMenuItem = contextmenu.add(
							0,
							CMO_EVENT_FORWARD,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_FORWARD);
					Item removeFromLocalMenuItem = contextmenu.add(
							0,
							CMO_EVENT_REMOVEFROMLOCAL, 
							KukkerApp.OptionsMenuLabel.CMO_EVENT_REMOVEFROMLOCAL);
					Item cancelMenuItem = contextmenu.add(
							0, 
							CMO_EVENT_CANCEL,
							KukkerApp.OptionsMenuLabel.CMO_EVENT_CANCEL		
					);

				}
				
				
				//
}catch(Exception e){
	Log.i("error",e.getMessage()+","+e.getCause());
}


			}
		};

	}

	public boolean onCreateOptionsMenu(Menu menu) {
		//NOTE: this method is called once by the framework therefore not seneitive to individual list item
		
		//KukkerApp.createOptionsMenu(menu);
		
		//Log.i("optionsmenu",this.getClass().getName()+", onCreateOptionsMenu");
		menu.setQwertyMode(false);
		
		SubMenu subMenu1 = menu.addSubMenu(0, 0, "Event",KukkerApp.Icons.OPTIONS_EVENT);
		subMenu1.setDefaultItem(KukkerApp.OptionsMenu.OMO_SHOWDETAILS);
		
		Item mi_showdetails = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_SHOWDETAILS, "Show event details",KukkerApp.Icons.OPTIONS_EVENT_SHOWDETAILS);
		mi_showdetails.setNumericShortcut('1');
				
		Item mi_new = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_CREATEEVENT, "Create new ",KukkerApp.Icons.OPTIONS_EVENT_CREATENEW);
		mi_new.setNumericShortcut('2');
		
		Item mi_forward = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_SENDTOFRIENDS, "Send to a friend",KukkerApp.Icons.OPTIONS_EVENT_SENDTOFRIENDS);
		mi_forward.setNumericShortcut('3');
		
		
		Item mi_edit = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_EDITEVENT, "Edit ",KukkerApp.Icons.OPTIONS_EVENT_EDIT);
		mi_edit.setNumericShortcut('4');
		
		
		Item mi_remove = subMenu1.add(0, KukkerApp.OptionsMenu.OMO_DELETEFROMLOCAL, "Delete",KukkerApp.Icons.OPTIONS_EVENT_DELETE);
		mi_remove.setNumericShortcut('0');
	
		SubMenu subMenu2 = menu.addSubMenu(0, 0, "Search",KukkerApp.Icons.OPTIONS_SEARCH);
		subMenu2.add(0, KukkerApp.OptionsMenu.OMO_SEARCHPUBLICEVENTS, "Public events",KukkerApp.Icons.OPTIONS_SEARCH_PUBLIC);
		subMenu2.add(0, KukkerApp.OptionsMenu.OMO_SEARCHSAVEDEVENTS, "Saved events",KukkerApp.Icons.OPTIONS_SEARCH_LOCAL);

		SubMenu subMenu3 = menu.addSubMenu(0, 0, "Help",KukkerApp.Icons.OPTIONS_HELP);
		subMenu3.add(0, KukkerApp.OptionsMenu.OMO_ABOUT, "About",KukkerApp.Icons.OPTIONS_HELP_ABOUT);
		subMenu3.add(0, 0, "Tips",KukkerApp.Icons.OPTIONS_HELP_TIPS);

		SubMenu subMenu4 = menu.addSubMenu(0, 0, "Options",KukkerApp.Icons.OPTIONS_OPTIONS);
		subMenu4.add(0, KukkerApp.OptionsMenu.OMO_PREFERENCES, "Preferences",KukkerApp.Icons.OPTIONS_PREFERENCES);

		
		
		return true;
	}

	public void onDestroy() {
		super.onDestroy();
		ser.stop();
		//Log.i("activity_process", this.getClass().getName() + " onDestroy ");
		this.dbHelper.close();
	}

	public void onFreeze(Bundle icicle) {
		super.onFreeze(icicle);
		//Log.i("activity_process", this.getClass().getName() + " onFreeze ");
	}

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		this.setTitle("Browse saved events");
		
		this.mResources = this.getResources();
		
		//	Retrieve screen dimension
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		this.screenHeight = dm.heightPixels;
		this.screenWidth = dm.widthPixels;
	
		//	Initialize
		this.initAnimations();
		this.initListeners();
		this.initDialogs();
		dbHelper = new DBHelper(this);		

		/*
		//	Setup webservice
		uws = new UpcomingWebService();
		uws.setOnEventFoundListener(this.mEventSearchUpcomingListener);
		uws.perPage = 50;
		uws.page = 1;
		 */
		
		//	progress bar
		boolean granted = requestWindowFeature(Window.FEATURE_PROGRESS);
		setProgressBarVisibility(false);

		setContentView(R.layout.upcoming_events_list);

		//	Obtain views
		this.eventDetailView = (EventDetailView) findViewById(R.id.kukkerevent_eventdetail);
		this.eventsSearchResultContainer = findViewById(R.id.events_search_result_container);
		this.eventLayout = findViewById(R.id.events_eventlayout);
		this.eventSearchInput = (SearchEventsInput) findViewById(R.id.eventsearchinput_searcheventsinput);
		this.eventsSearchInputContainer = findViewById(R.id.eventsearchinput_container);
		this.eventListView = (KukkerListView) getListView();
		this.eventListView.setEmptyView(findViewById(R.id.empty));

		// 	Set up adapters
		eventListAdapter = new KukkerListAdapter(this);		
		eventListAdapter.setListView(eventListView);
		eventListView.setAdapter(eventListAdapter);

		// ContextMenuWatcher
		eventListView.setContextMenuWatcher(this);
		
		// 	Wire up events listeners
		eventDetailView.setListener(this.mEventDetailViewListener);
		eventListView.setKukkerListItemListener(this.mKukkerListItemListener);		
		eventSearchInput.setSearchEventsInputListener(this.mSearchEventsInputListener);
		eventListView.setOnPopulateContextMenuListener(this.mOnPopulateContextMenuListener);

		/*
		 * setProgressBarVisibility(true); setProgress(5000);
		 * setProgressBarIndeterminate(false); setProgressBarVisibility(true);
		 */
	
		// 	Initial focus and events detection configuration.
		eventListView.setDetectIncomingEvents(true);
		eventDetailView.setDetectIncomingEvents(false);
		eventSearchInput.setDetectIncomingEvents(false);
		eventsSearchInputContainer.setVisibility(View.GONE);
		
		//	Load events to list
		this.loadEventsList();
	}
	
	private void initDialogs(){
		this.initDialogSearch();
		this.initDialogPreferences();
		this.initDialogAbout();
	}
	
	private void initDialogAbout(){
		mDialogAbout = new AboutDialog(this);
				
	}
	private void initDialogSearch(){
		mDialogSearch = new Dialog(BrowseSavedEventsActivity.this);
		mDialogSearch.setContentView(R.layout.dialog_searchevent);
		mDialogSearch.setTitle("Search public events");
		Button searchButton = (Button) mDialogSearch.findViewById(R.id.eventsearchinput_button_search);
		searchButton.setOnClickListener(new OnClickListener(){
			public void onClick(View arg0) {
				SearchEventsInput esi = (SearchEventsInput) mDialogSearch.findViewById(R.id.eventsearchinput_searcheventsinput);
				Properties searchParams = esi.getSearchParameters();				
				searchPublicEvents(searchParams);
				mDialogSearch.dismiss();
			}
		});
	}
	
	
	
	
	
	private void initDialogPreferences(){
		this.mDialogPreferences = new PreferenceDialog(this);		
	}
	
	
	private void loadEventsList(){
		//Event eventTemplate[] = new Event[0];
		Event events[] = this.dbHelper.fetchAllEvents();		
		this.eventListAdapter.setData(events);
		this.eventListAdapter.notifyDataSetChanged();		
	}

	/*
	private synchronized void updateResultsList(Properties params) {
		Event events[] = this.invokeSearch(params);
		Log.i("Upcoming", "Num events:" + events.length);


	}
	*/
	
	private void showEventDetails(Event data,int lastSelectedPosition, KukkerListItemView itemView){
		mUserActivity = UserActivity.VIEW_EVENTDETAILS;
		eventListView.setLastSelectedItemPosition(lastSelectedPosition);
		eventListView.setLastSelectedItem(itemView);
		event0 = data;
		//eventListView.setActivated(false); //IMPORTANT 
		if(itemView == null){
			//Log.i("agus","itemView is null");
		}
	//	Log.i("agus","last selected position :"+lastSelectedPosition);
		
		doAnim1();
	}
	
	private View subView1;

	// private int subView1_id = 2;

	private void createSubViews() {
		subView1 = new LinearLayout(this);
		subView1.setBackgroundColor(Color.RED);
		TextView tv = new TextView(this);
		tv.setText("HelloWorld");
		tv.setTextColor(Color.WHITE);
		tv.setTextSize(20);

		Button btn = new Button(this);
		btn.setText("Button");

		btn.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		((ViewGroup) subView1).addView(btn);

		tv.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		((ViewGroup) subView1).addView(tv);

		subView1.setLayoutParams(new AbsoluteLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1, 1));

		// findViewById(id);
		FrameLayout fl = (FrameLayout) this
				.findViewById(R.id.events_list_framelayout_0);
		fl.addView(subView1);
	}

	/*
	 * protected void onListItemClick(ListView l, View v, int position, long id) {
	 * //Log.i("DEBUG", "onListItemCLick:" + position); //Adapter adapter =
	 * this.getListView().getAdapter();
	 * //this.getListView().setOnItemClickListener((OnItemClickListener) this); //
	 * ((EventListAdapter)adapter).toggle(position); }
	 */

	/*
	protected Event[] invokeSearch(Properties params) {
		// String apiKey = "6efc1a7606";
		uws.setMethod(UpcomingWebService.Method.EVENT_SEARCH);
		uws.setParameters(params);
		Log.i("webservice", params.getProperty("location"));
		Event[] events = uws.get();

		return events;

	}
	*/

	private DocumentImpl getMockData() {

		DocumentBuilderFactory dbf1 = DocumentBuilderFactory.newInstance();

		dbf1.setValidating(false);
		dbf1.setExpandEntityReferences(true);
		dbf1.setIgnoringComments(true);
		dbf1.setNamespaceAware(false);

		DocumentBuilder db;
		// XmlPullParser xmlpullparser =
		// this.getResources().getXml(R.xml.eventsearch);
		// xmlpullparser.

		try {
			db = dbf1.newDocumentBuilder();
			// InputSource inputSource = new InputSource();
			// StringReader stringReader = new StringReader();
			File xmlfile0 = new File("/data/data/org.kukker", "eventsearch.xml");

			DocumentImpl doc = (DocumentImpl) db.parse(xmlfile0);

			return doc;
		} catch (ParserConfigurationException e) {
		//	Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			//Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			//Log.i("Kukker", "getMockData " + e.getMessage());
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;

	}

	// / CONTEXT MENU HANDLING

	public boolean onOptionsItemSelected(Item item) {

		super.onOptionsItemSelected(item);
		
		
		int pos = eventListView.getSelectedItemPosition();		
		KukkerListItemView view = (KukkerListItemView)eventListView.getSelectedView();		
		Event data = (Event) eventListView.getAdapter().getItem(pos);
		
		
		
		switch (item.getId()) {
			case KukkerApp.OptionsMenu.OMO_CREATEEVENT:
				this.startSubActivity(new Intent(BrowseSavedEventsActivity.this,CreateNewEventActivity.class),KukkerApp.ACTIVITY_EVENTCREATE);
				break;
			case KukkerApp.OptionsMenu.OMO_SEARCHPUBLICEVENTS:
				this.startSubActivity(new Intent(BrowseSavedEventsActivity.this,SearchEventsActivity.class),KukkerApp.ACTIVITY_EVENTSEARCH);
				break;
			case KukkerApp.OptionsMenu.OMO_SHOWDETAILS:
				if(view != null && data != null){
					showEventDetails(data,pos,view);
				}
				break;
			case KukkerApp.OptionsMenu.OMO_DELETEFROMLOCAL:
				if(view != null && data != null){
					removeEvent(data, view);
				}
				break;
			case KukkerApp.OptionsMenu.OMO_EDITEVENT:
				//Intent i = new Intent(BrowseSavedEventsActivity.this,CreateNewEventActivity.class),KukkerApp.ACTIVITY_EVENTCREATE				
				//this.startSubActivity();
			case KukkerApp.OptionsMenu.OMO_PREFERENCES:
				this.mDialogPreferences.show();
				break;
			case KukkerApp.OptionsMenu.OMO_ABOUT:
				this.mDialogAbout.show();
				break;
			default:
				break;			
		}
	
		return true;
	}
	
	public void onActivityResult(int requestCode, int resultCode, String data,Bundle extras){
		if(requestCode == KukkerApp.ACTIVITY_EVENTCREATE){
			this.loadEventsList();			
		}
		else 
		if(requestCode == KukkerApp.ACTIVITY_EVENTSEARCH){
			this.loadEventsList();			
		}
		
	}

	// / CONTEXT MENU HANDLING

	public boolean onContextItemSelected(Item item) {
		super.onContextItemSelected(item);

		ContextMenuInfo menuInfo = (ContextMenuInfo) item.getMenuInfo();
		KukkerListItemView itemView = (KukkerListItemView) menuInfo.targetView;

		// Object obj = view.getListView();
		// Log.i("debug","onContextItemSelected: view:" +
		// view.getClass().getSimpleName());
		// Log.i("debug","onContextItemSelected: view.getListView:" +
		// obj.getClass().getSimpleName());

		Event data = null;
		int lastSelectedPosition = 0;
		
		if (itemView != null) {
			KukkerListView listView = itemView.getListView();
			// Log.i("debug","LISTVIEW:"+listView.toString());
			lastSelectedPosition = listView.getLastPressedDownItemPosition(); // use hack
			data = (Event) eventListView.getAdapter()
					.getItem(menuInfo.position);
		}

		switch (item.getId()) {
		case KukkerApp.OptionsMenu.CMO_EVENT_CANCEL:
			break;
		case KukkerApp.OptionsMenu.CMO_EVENT_SAVETOLOCAL:
			if (data != null) {
				saveEvent(data, itemView);
			}
			break;

		case KukkerApp.OptionsMenu.CMO_EVENT_FORWARD:
			break;
			
		case KukkerApp.OptionsMenu.CMO_EVENT_SHOWDETAILS:
			
			this.showEventDetails(data, lastSelectedPosition, itemView);
			break;
		case KukkerApp.OptionsMenu.CMO_EVENT_REMOVEFROMLOCAL:
			if (data != null && itemView != null) {
				this.removeEvent(data, itemView);
			}
			break;
		default: 
			break;
		}
		return true;
	}

	/**
	 * Removes event from phone
	 * 
	 * @param data
	 * @param view
	 */
	private void removeEvent(Event data, KukkerListItemView view) {
		if (data == null) {
			return;
		}
		//this.dbHelper.deleteEventUsingRemoteId(data.remoteId);
		this.dbHelper.deleteEvent(data.id);
		data.setIsSaved(false);
		view.updateView();
		this.loadEventsList();
	}
	
	private void searchPublicEvents(Properties params){
		ser = new SearchEventsRunnable();
		ser.setSearchParameters(params);
		Handler handler = KukkerApp.mUpcomingLocalService.mServiceHandler;
		handler.post(ser);	
	}

	/**
	 * Saves event to phone
	 * 
	 * @param data
	 * @param view
	 */
	private void saveEvent(Event data, KukkerListItemView view) {
		// Event data = (Event) eventListView.getSelectedItem();
		// KukkerListItemView view = (KukkerListItemView)
		// eventListView.getSelectedView();

		// check if selected data has been saved to local

		if (data == null) {
			//Log.i("debug", "no data found");
			return;
		}

		boolean hasBeenSaved = data.getIsSaved();

		if (!hasBeenSaved) {
			// save it to local

			// Object data =
			// eventListAdapter.getItem(listItemView.getPosition());

			/*
			Log.i("save0", this.getClass().getName()
					+ ", saveEvent(), remoteId: "
					+ ((UpcomingEvent) data).remoteId + "");
*/
			
			// TODO: impl saving branching based on data type
			// saveEvent((UpcomingEvent) data);
			long newRowId = this.dbHelper.insertEvent(data, ORIGIN_ID_UPCOMING);

			if (newRowId != -1) {
				// set a flag
				data.setIsSaved(true);
				data.id = (int) newRowId;
				// redisplay view
				view.updateView();
			}

		} else {
			// delete local data

			int remoteId = ((UpcomingEvent) data).remoteId;
			dbHelper.deleteEventUsingRemoteId(remoteId);
			data.setIsSaved(false);
			view.updateView();

		}

	}

	// / animation

	int sw = 319;

	TranslateAnimation animation_searchresults_show;
	TranslateAnimation animation_searchresults_hide;
	AnimationListener animationListener_searchresults_show;
	AnimationListener animationListener_searchresults_hide;
	boolean isStarted_animation_searchResults_show = false;
	boolean isStarted_animation_searchResults_hide = false;

	TranslateAnimation animation_eventsearchinput_show;
	TranslateAnimation animation_eventsearchinput_hide;
	AnimationListener animationListener_eventsearchinput_show;
	AnimationListener animationListener_eventsearchinput_hide;
	boolean isStarted_animation_searchinput_show = false;
	boolean isStarted_animation_searchinput_hide = false;

	private void initAnimations() {

		this.animation_searchresults_show = new TranslateAnimation(0,
				-this.screenWidth, 0, 0);
		this.animation_searchresults_hide = new TranslateAnimation(0,
				this.screenWidth, 0, 0);

		this.animation_eventsearchinput_show = new TranslateAnimation(0, 0, 0,
				this.screenHeight);
		this.animation_eventsearchinput_hide = new TranslateAnimation(0, 0, 0,
				-this.screenHeight);

		this.initAnimationListeners();

		this.init_anim_searchresults();
		this.init_anim_searchinput();

		// eventsSearchResultContainer.setDrawingCacheEnabled(true);
		// eventsSearchResultContainer.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
	}

	private void init_anim_searchresults() {
		animation_searchresults_show
				.setAnimationListener(animationListener_searchresults_show);
		animation_searchresults_show.setStartOffset(300);
		animation_searchresults_show.setDuration(800);

		animation_searchresults_hide
				.setAnimationListener(animationListener_searchresults_hide);
		animation_searchresults_hide.setStartOffset(300);
		animation_searchresults_hide.setDuration(800);
	}

	private void init_anim_searchinput() {
		animation_eventsearchinput_show
				.setAnimationListener(animationListener_eventsearchinput_show);
		animation_eventsearchinput_show.setStartOffset(300);
		animation_eventsearchinput_show.setDuration(1000);

		animation_eventsearchinput_hide
				.setAnimationListener(animationListener_eventsearchinput_hide);
		animation_eventsearchinput_hide.setStartOffset(300);
		animation_eventsearchinput_hide.setDuration(1000);
	}

	private void initAnimationListeners() {

		// hide event details, show search results
		this.animationListener_searchresults_show = new AnimationListener() {
			public void onAnimationEnd() {
				//Log.i("debug", "end anim");
				LayoutParams lp = eventsSearchResultContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.x = 0;

				//
				eventsSearchResultContainer.setLayoutParams(allp);

				eventDetailView.setDetectIncomingEvents(false);
				eventListView.setDetectIncomingEvents(true);

				// eventListView.setBlockChildEvents(false);
				eventListView.setFocusableInTouchMode(true);

				// eventLayout.requestFocus();
				// animation_searchResults_show.reset();

				isStarted_animation_searchResults_show = false;
				eventsSearchResultContainer.clearAnimation();

			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				// eventDetailView.setDetectIncomingEvents(false);
				// eventListView.setDetectIncomingEvents(true);
				//Log.i("debug", "start anim");
				// eventDetailView.setVisibility(View.GONE);

			}
		};

		/**
		 * show event details
		 */
		this.animationListener_searchresults_hide = new AnimationListener() {
			public void onAnimationEnd() {
				//Log.i("debug", "end anim");

				LayoutParams lp = eventsSearchResultContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.x = screenWidth - 1;

				eventsSearchResultContainer.setLayoutParams(allp);
				eventDetailView.requestFocus();

				isStarted_animation_searchResults_hide = false;
				eventsSearchResultContainer.clearAnimation();
			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				//Log.i("debug", "start anim");
				eventDetailView.populateEventDetailsView(event0);
				eventListView.setDetectIncomingEvents(false);
				eventDetailView.setDetectIncomingEvents(true);
				eventDetailView.scrollTo(0, 0);
				// eventListView.setActivated(false);
				// eventListView.storeLastSelectedItem();

			}
		};

		// //////

		// show searchinput
		this.animationListener_eventsearchinput_show = new AnimationListener() {
			public void onAnimationEnd() {
				LayoutParams lp = eventsSearchInputContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.y = 0;
				eventsSearchInputContainer.setLayoutParams(allp);

				eventSearchInput.requestFocus();

				eventsSearchInputContainer.clearAnimation();
				isStarted_animation_searchinput_show = false;
			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				eventListView.setDetectIncomingEvents(false);
				eventSearchInput.setDetectIncomingEvents(true);
			}
		};

		/**
		 * hide search input hide event search input ---- to show ---> hidden
		 * search results list
		 */
		this.animationListener_eventsearchinput_hide = new AnimationListener() {
			public void onAnimationEnd() {
				//Log.i("debug", "anim list, onAnimEnd");
				LayoutParams lp = eventsSearchInputContainer.getLayoutParams();
				AbsoluteLayout.LayoutParams allp = ((AbsoluteLayout.LayoutParams) lp);
				allp.y = -screenHeight;
				eventsSearchInputContainer.setLayoutParams(allp);

				// eventSearchInput.setDetectIncomingEvents(false);
				eventListView.setDetectIncomingEvents(true);
				// eventListView.setBlockChildEvents(false);

				isStarted_animation_searchinput_hide = false;
				eventsSearchInputContainer.clearAnimation();

			}

			public void onAnimationRepeat() {
			}

			public void onAnimationStart() {
				//Log.i("debug", "anim list, onAnimStart, h:" + screenHeight);
				// eventListView.setDetectIncomingEvents(true);
				eventSearchInput.setDetectIncomingEvents(false);
				// eventDetailView.scrollTo(0,0);
			}
		};
	}

	// hide search results
	private void doAnim1() {
		if (!isStarted_animation_searchResults_hide && !isStarted_animation_searchResults_show) {
			//Log.i("debug", "doAnim1");
			// eventsSearchResultContainer.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
			eventsSearchResultContainer
					.startAnimation(animation_searchresults_hide);
			isStarted_animation_searchResults_hide = true;
		} else {

		}
	}

	// show search results
	private void doAnim2() {
		if (!isStarted_animation_searchResults_show && !isStarted_animation_searchResults_hide) {
			//Log.i("debug", "doAnim2");
			eventsSearchResultContainer
					.startAnimation(animation_searchresults_show);
			isStarted_animation_searchResults_show = true;
		} else {

		}
	}

	/**
	 * Show event search input
	 */
	private void doAnim3() {

		if (!isStarted_animation_searchinput_show) {
			eventListView.storeLastSelectedItem();
			// eventListView.setActivated(false);

			eventsSearchInputContainer
					.startAnimation(animation_eventsearchinput_show);
			isStarted_animation_searchinput_show = true;
		} else {

		}

	}

	/**
	 * Hide event search input
	 */
	private void doAnim4() {

		if (!isStarted_animation_searchinput_hide) {
			//Log.i("debug", "inside doanim4");
			eventsSearchInputContainer
					.startAnimation(animation_eventsearchinput_hide);
			isStarted_animation_searchinput_hide = true;
		} else {

		}
	}

	class SearchEventsRunnable implements Runnable {

		Properties searchParams;

		public void setSearchParameters(Properties params) {
			this.searchParams = params;
		}

		private boolean isRunning = false;

		public void stop() {
			this.isRunning = false;
		}

		ArrayList<Event> events = new ArrayList<Event>();
		Event[] eventsArr = null;
		Runnable updateList = new Runnable() {
			@Override
			public void run() {

				//Log.i("service2", " updating list");
				// TODO Auto-generated method stub

				eventListAdapter.setData(eventsArr);
				eventListAdapter.notifyDataSetChanged();
				setProgressBarIndeterminate(true);
				// eventListAdapter.notifyDataSetInvalidated();
			}
		};

		Runnable updateProgress = new Runnable() {
			public void run() {
				//setProgressBarVisibility(false);
				setProgressBarVisibility(true);
			}
		};

		@Override
		public void run() {
			this.isRunning = true;

			boolean keepFetching = true;
			uws.setMethod(UpcomingWebService.Method.EVENT_SEARCH);
			uws.setParameters(this.searchParams);

			int perPage = 10;
			int maxResults = 100;
			int totalFound = 0;

			uws.page = 1;
			uws.perPage = perPage;

			// set progress bar type
			runOnUIThread(new Runnable() {
				public void run() {
					setProgressBarIndeterminate(true);
				}
			});

			while (keepFetching && isRunning) {
				int numAdded = uws.get(events);
				totalFound += numAdded;

				// events = invokeSearch(this.searchParams);
				//Log.i("service2", "found: " + numAdded);
				if (numAdded == perPage) {
					uws.page = uws.page + 1;
					Event[] contents = new Event[1];
					eventsArr = events.toArray(contents);
					runOnUIThread(updateProgress);
					runOnUIThread(updateList);
				} else {
					runOnUIThread(new Runnable() {
						public void run() {
							setProgressBarVisibility(false);
						}
					});
					keepFetching = false;
				}

				if (totalFound >= maxResults) {
					isRunning = false;

					// hide progress bar
					runOnUIThread(new Runnable() {
						public void run() {
							setProgressBarVisibility(false);
						}
					});
					keepFetching = false;
				}

			}
		}
	}

	@Override
	public boolean isContextMenuShown() {
		// TODO Auto-generated method stub
		return this.mContextIsShown;
	}
}
